<template>
  <div>
    <div class="bannerTop">
      <img
        src="https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/bg_msg_title.png"
      />
      <div class="contDiv">
        <div>
          <p>今日销售额(元)</p>
          <span>￥ {{dataInfo.orderAmount}}</span>
        </div>
        <div>
          <p>今日订单数</p>
          <span>{{dataInfo.orderNum}}</span>
        </div>
        <div>
          <p>今日返佣(元)</p>
          <span>￥ {{dataInfo.rebateAmount}}</span>
        </div>
      </div>
    </div>
    <div class="infoShow">
      <div class="sonDiv" v-for="(item,index) in blockList" :key="index">
        <p>{{countForm[item.key]}}</p>
        <span>{{item.name}}</span>
      </div>
    </div>
    <div class="showDataType">
      <div
        v-for="(item,index) in showDataTypeList"
        :key="index"
        :class="item.isClick ? 'isClick' : ''"
        @click="showDataTypeClick(item)"
      >
        <div class="top">
          <img :src="item.src" />
          <span>{{item.name}}</span>
        </div>
        <p v-if="item.isMoney">￥{{dynamicDataInfo[item.key]}}</p>
        <p v-else>{{dynamicDataInfo[item.key]}}</p>
      </div>
    </div>

    <div class="chart-wrap">
      <mpvue-echarts
        :echarts="echarts"
        ref="echarts"
        :on-init="initChart"
        throttle-touch
        lazyLoad
      />
    </div>

    <div class="showDataDate">
      <div
        v-for="(item,index) in showDataDateList"
        :key="index"
        :class="item.isClick ? 'isClick' : ''"
        @click="showDataDateClick(item)"
      >
        <picker
          v-if="item.state"
          mode="date"
          class="filter-picker"
          @change="handleYearChange"
        >{{item.name}}</picker>
        <span v-else>{{item.name}}</span>
      </div>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/bar'
// import echarts from 'echarts/dist/diy_echarts'
// import echarts from 'echarts'

import mpvueEcharts from 'mpvue-echarts'
import {
  SHOP_SALES_COUNT_DAY, // 店铺每天订单统计
  SHOP_SALES_COUNT_MONTH, // 订单统计（月）
  COUNT_MONTHLY_REBATE_API_DAY, // 每天返佣统计
  COUNT_MONTHLY_REBATE_API_MONTH, // 返佣统计（月）
  FIND_CUSTOMER_PAGE_API, // 会员数
  SHOP_EVALUATION_COUNT, // 评分率
  SHOP_COLLECTION_COUNT, // 收藏数
  FIND_SHOP_ORDER_PAGE // 订单数
} from '@/api'
import { dateFormatter, getCurrentPageParams } from '@/utils'
import moment from 'moment'

import chartOption from './chart3'
let chart = null

export default {
  components: { mpvueEcharts },
  props: {},
  data () {
    return {
      echarts,
      salesData: [],
      isDay: true,
      monthList: [],
      dataInfo: {
        orderAmount: 0,
        orderNum: 0,
        rebateAmount: 0
      },
      dynamicDataInfo: {
        orderAmount: 0,
        orderNum: 0,
        rebateAmount: 0
      },
      countForm: {
        memberTotal: 0,
        score: 0,
        collect: 0,
        orderTotal: 0
      },
      form: { orderDateStart: '', orderDateEnd: '' },
      showDataTypeList: [
        {
          name: '销售总额',
          src:
            'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/rec_blue.png',
          key: 'orderAmount',
          isClick: true,
          isMoney: true
        },
        {
          name: '订单数量',
          src:
            'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/rec_green.png',
          key: 'orderNum',
          isClick: false,
          isMoney: false
        },
        {
          name: '返佣金额',
          src:
            'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/rec_yellow.png',
          key: 'rebateAmount',
          isClick: false,
          isMoney: true
        }
      ],
      showDataDateList: [
        {
          name: '近7日',
          key: '7',
          state: false,
          isClick: true
        },
        {
          name: '近30日',
          key: '30',
          state: false,
          isClick: false
        },
        {
          name: '近三月',
          key: '90',
          state: false,
          isClick: false
        },
        {
          name: '自定义时间',
          key: '0',
          state: true,
          isClick: false
        }
      ],
      orderType: 'orderAmount', // 默认是销售总额
      dateTiem: '7' // 默认是7天
    }
  },
  computed: {
    account () {
      return this.$store.state.account
    },
    blockList () {
      return [
        {
          name: '会员数',
          key: 'memberTotal'
        },
        {
          name: '评分率',
          key: 'score'
        },
        {
          name: '收藏数',
          key: 'collect'
        },
        {
          name: '订单数',
          key: 'orderTotal'
        }
      ]
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    console.log('type：', getCurrentPageParams('type'))
    this.init()
    this.initRequest()
  },
  methods: {
    showDataTypeClick (item) {
      const vm = this
      vm.salesData = []
      vm.monthList = []
      vm.showDataTypeList.forEach(_ => {
        _.isClick = false
        if (_.key === item.key) {
          vm.orderType = _.key
          _.isClick = true
          let start = new Date(vm.form.orderDateStart)
          let end = new Date(vm.form.orderDateEnd)
          let time = 3600 * 24 * 1000 * 6
          if (end - start <= time) {
            vm.shopSalesCountDay()
            vm.rebateASalesCountDay()
          } else {
            vm.shopSalesCount()
            vm.rebateASalesCount()
          }
        }
      })
    }, // 选类型
    showDataDateClick (item) {
      const vm = this
      vm.salesData = []
      vm.monthList = []
      vm.showDataDateList.forEach(_ => {
        _.isClick = false
        if (_.key === item.key) {
          _.isClick = true
          if (!_.state) {
            let val = item.key
            if (val === '7') {
              let startDate = moment(
                new Date().getTime() - 3600 * 24 * 1000 * 6
              ).format('YYYY-MM-DD')
              vm.form.orderDateStart = startDate
              vm.form.orderDateEnd = dateFormatter('yyyy-MM-dd', new Date())
              vm.shopSalesCountDay()
              vm.rebateASalesCountDay()
            } else if (val === '30') {
              let startDate2 = moment(
                new Date().getTime() - 3600 * 24 * 1000 * 30
              ).format('YYYY-MM-DD') // 后面改成30天了
              let endDate = moment(new Date()).format('YYYY-MM-DD')
              vm.form.orderDateStart = startDate2
              vm.form.orderDateEnd = endDate
              vm.shopSalesCount()
              vm.rebateASalesCount()
            } else if (val === '90') {
              let startDate = moment(
                new Date().getTime() - 3600 * 24 * 1000 * 90
              ).format('YYYY-MM-DD')
              let endDate = moment(new Date()).format('YYYY-MM-DD')
              vm.form.orderDateStart = startDate
              vm.form.orderDateEnd = endDate
              vm.shopSalesCount()
              vm.rebateASalesCount()
            } else {
              vm.$total('数据有误')
            }
          }
        }
      })
    }, // 选择时间
    handleYearChange (e) {
      const vm = this
      let value = e.target.value
      vm.form.orderDateEnd = value
      let start = dateFormatter('yyyy-MM-dd', new Date())
      vm.form.orderDateStart = start
      let end = new Date(vm.form.orderDateEnd)
      let time = 3600 * 24 * 1000 * 6
      if (end - start <= time) {
        vm.shopSalesCountDay()
        vm.rebateASalesCountDay()
      } else {
        vm.shopSalesCount()
        vm.rebateASalesCount()
      }
    },
    init () {
      const vm = this
      vm.form.orderDateStart = moment(
        new Date().getTime() - 3600 * 24 * 1000 * 6
      ).format('YYYY-MM-DD')

      vm.form.orderDateEnd = dateFormatter('yyyy-MM-dd', new Date())
      vm.rebateASalesCountDay()
      vm.shopSalesCountDay()
    },
    shopSalesCountDay () {
      const vm = this
      vm.isDay = true
      let params = {
        ...vm.form,
        state: '3',
        shopId: vm.account.shopId
      }
      params.orderDateStart = `${vm.form.orderDateStart} 00:00:00`
      params.orderDateEnd = `${vm.form.orderDateEnd} 23:59:59`
      SHOP_SALES_COUNT_DAY(params)
        .then(r => {
          if (r.data.code === '0') {
            let arr = r.data.data
            let val = arr.reduce((acc, _) => {
              acc += _.saleAmount
              return acc
            }, 0)
            let num = arr.reduce((acc, _) => {
              acc += _.saleNum
              return acc
            }, 0)
            if (arr.length) {
              arr.forEach(_ => {
                _.saleAmount = _.saleAmount.toFixed(2)
              })
            }
            vm.dynamicDataInfo.orderAmount = val.toFixed(2)
            vm.dynamicDataInfo.orderNum = num

            if (vm.orderType !== 'rebateAmount') {
              let data = arr
              let dataList = []

              let dayList = new Date(this.form.orderDateEnd).valueOf()
              let newList = Array.from(
                new Array(7),
                (_, i) =>
                  dateFormatter(
                    'dd',
                    new Date(dayList - (6 - i) * (1000 * 60 * 60 * 24))
                  ) * 1
              )
              for (let i = 0; i < newList.length; i++) {
                let obj = {
                  saleAmount: '0',
                  saleNum: 0
                }
                for (let j = 0; j < data.length; j++) {
                  if (
                    newList[i] ===
                    Number(data[j].orderDate.split(' ')[0].split('-')[2])
                  ) {
                    obj.saleAmount = data[j].saleAmount
                    obj.saleNum = data[j].saleNum
                  }
                }
                dataList.push(obj)
              }
              // vm.refreshChart(data.sort((a, b) => a.month - b.month))
              vm.refreshChart(dataList)
            }
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 订单统计（天）
    shopSalesCount () {
      const vm = this
      vm.isDay = false
      let params = {
        ...vm.form,
        state: '3',
        shopId: vm.account.shopId
      }
      params.orderDateStart = `${vm.form.orderDateStart} 00:00:00`
      params.orderDateEnd = `${vm.form.orderDateEnd} 23:59:59`
      SHOP_SALES_COUNT_MONTH(params)
        .then(r => {
          if (r.data.code === '0') {
            let arr = r.data.data
            vm.monthList = []
            arr.forEach(_ => {
              vm.monthList.push(`${_.month}月`)
            })
            let val = arr.reduce((acc, _) => {
              acc += _.saleAmount
              return acc
            }, 0)
            let num = arr.reduce((acc, _) => {
              acc += _.saleNum
              return acc
            }, 0)
            if (arr.length) {
              arr.forEach(_ => {
                _.saleAmount = _.saleAmount.toFixed(2)
              })
            }
            vm.dynamicDataInfo.orderAmount = val.toFixed(2)
            vm.dynamicDataInfo.orderNum = num

            if (vm.orderType !== 'rebateAmount') {
              let data = arr
              vm.refreshChart(data.sort((a, b) => a.month - b.month))
            }
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 订单统计（月）
    rebateASalesCountDay () {
      const vm = this
      vm.isDay = true
      let params = {
        ...vm.form,
        relateId: vm.account.shopId,
        identity: 'SHOP',
        state: '1'
      }
      params.createDateStart = `${vm.form.orderDateStart} 00:00:00`
      params.createDateEnd = `${vm.form.orderDateEnd} 23:59:59`
      delete params.orderDateStart
      delete params.orderDateEnd
      COUNT_MONTHLY_REBATE_API_DAY(params)
        .then(r => {
          if (r.data.code === '0') {
            let arr = r.data.data
            let val = arr.reduce((acc, _) => {
              acc += _.amount * 0.01 + _.point * 0.0001
              return acc
            }, 0)
            if (arr.length) {
              arr.forEach(_ => {
                _.amount = _.amount.toFixed(2)
              })
            }
            vm.dynamicDataInfo.rebateAmount = val.toFixed(2)
            if (vm.orderType === 'rebateAmount') {
              let data = arr
              let dayList = new Date(this.form.orderDateEnd).valueOf()
              let newList = Array.from(
                new Array(7),
                (_, i) =>
                  dateFormatter(
                    'dd',
                    new Date(dayList - (6 - i) * (1000 * 60 * 60 * 24))
                  ) * 1
              ).map(_ => ({
                day: _
                // amount: 0,
                // point: 0
              }))

              let newList2 = data.map(_ => ({
                ..._,
                day: Number(_.createDate.split(' ')[0].split('-')[2])
              }))
              newList.forEach(_ => {
                newList2.forEach(e => {
                  if (_.day === e.day) {
                    _.amount = (e.amount * 0.01 + e.point * 0.0001).toFixed(2)
                  }
                })
              })

              // vm.refreshChart(data.sort((a, b) => a.month - b.month))
              vm.refreshChart(newList)
            }
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 返佣金额（天）
    rebateASalesCount () {
      const vm = this
      vm.isDay = false
      let params = {
        ...vm.form,
        relateId: vm.account.shopId,
        identity: 'SHOP',
        state: '1'
      }
      params.createDateStart = `${vm.form.orderDateStart} 00:00:00`
      params.createDateEnd = `${vm.form.orderDateEnd} 23:59:59`
      delete params.orderDateStart
      delete params.orderDateEnd
      COUNT_MONTHLY_REBATE_API_MONTH(params)
        .then(r => {
          if (r.data.code === '0') {
            let arr = r.data.data
            vm.monthList = []
            arr.forEach(_ => {
              vm.monthList.push(`${_.month}月`)
            })
            let val = arr.reduce((acc, _) => {
              acc += _.amount * 0.01 + _.point * 0.0001
              return acc
            }, 0)
            if (arr.length) {
              arr.forEach(_ => {
                _.amount = (_.amount * 0.01 + _.point * 0.0001).toFixed(2)
              })
            }
            vm.dynamicDataInfo.rebateAmount = val.toFixed(2)

            if (vm.orderType === 'rebateAmount') {
              let data = arr
              vm.refreshChart(data.sort((a, b) => a.month - b.month))
            }
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 返佣金额（月）
    initChart (canvas, width, height) {
      chart = echarts.init(canvas, null, { width, height })
      canvas.setChart(chart)
      let option = chartOption
      let keys = ['saleAmount'] // 默认的
      let name = '单位：元'
      if (this.orderType === 'orderAmount') {
        name = '单位：元'
        keys = ['saleAmount']
      } else if (this.orderType === 'orderNum') {
        name = '单位：次'
        keys = ['saleNum']
      } else {
        name = '单位：元'
        keys = ['amount']
      }
      keys.forEach((key, idx) => {
        option.series[idx].data = this.salesData.map(_ => _[key])
        option.yAxis[idx].name = name
        option.series[idx].name = name
      })

      if (this.isDay) {
        let dayList = new Date(this.form.orderDateEnd).valueOf()
        option.xAxis.data = Array.from(
          new Array(7),
          (_, i) =>
            dateFormatter(
              'dd',
              new Date(dayList - (6 - i) * (1000 * 60 * 60 * 24))
            ) *
              1 +
            '日'
        )
      } else {
        // option.xAxis.data = Array.from(new Array(12), (_, i) => `${i + 1}月`)
        option.xAxis.data = this.monthList
      }

      chart.setOption(option)
      return chart
    },
    refreshChart (list) {
      this.salesData = list
      this.$refs.echarts.init()
    },

    /** 这个下面是固定了的，今本上不会变得数据 **/
    shopSalesCountDay1 () {
      const vm = this
      let day = dateFormatter('yyyy-MM-dd', new Date())
      let params = {
        shopId: vm.account.shopId,
        state: '3'
      }
      params.orderDateStart = `${day} 00:00:00`
      params.orderDateEnd = `${day} 23:59:59`
      SHOP_SALES_COUNT_DAY(params)
        .then(r => {
          if (r.data.code === '0') {
            let arr = r.data.data
            let val = arr.reduce((acc, _) => {
              acc += _.saleAmount
              return acc
            }, 0)
            let num = arr.reduce((acc, _) => {
              acc += _.saleNum
              return acc
            }, 0)
            if (arr.length) {
              arr.forEach(_ => {
                _.saleAmount = _.saleAmount.toFixed(2)
              })
            }
            vm.dataInfo.orderAmount = val.toFixed(2)
            vm.dataInfo.orderNum = num
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 订单统计（固定了的每天）
    rebateASalesCountDay1 () {
      const vm = this
      let params = {
        relateId: vm.account.shopId,
        identity: 'SHOP',
        state: '1'
      }
      let day = dateFormatter('yyyy-MM-dd', new Date())
      params.createDateStart = `${day} 00:00:00`
      params.createDateEnd = `${day} 23:59:59`
      COUNT_MONTHLY_REBATE_API_DAY(params)
        .then(r => {
          if (r.data.code === '0') {
            let arr = r.data.data
            let val = arr.reduce((acc, _) => {
              acc += _.amount * 0.01 + _.point * 0.0001
              return acc
            }, 0)
            vm.dataInfo.rebateAmount = val.toFixed(2)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 返佣金额（固定了的每天）
    _getVIPNumPeople () {
      const vm = this
      let params = {
        shopId: vm.account.shopId
      }
      FIND_CUSTOMER_PAGE_API(params, 1, 1)
        .then(r => {
          if (r.data.code === '0') {
            vm.countForm.memberTotal = r.data.data.total
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    }, // 会员数
    shopEvaluationCount () {
      const vm = this
      SHOP_EVALUATION_COUNT(vm.account.shopId)
        .then(r => {
          if (r.data.code === '0') {
            vm.countForm.score = r.data.data.shopAssessAvg
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 评分率
    shopCollectionCount () {
      const vm = this
      SHOP_COLLECTION_COUNT(vm.account.shopId)
        .then(r => {
          if (r.data.code === '0') {
            vm.countForm.collect = r.data.data
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 收藏数
    shopOrderCount () {
      const vm = this

      let params = {
        shopId: vm.account.shopId,
        state: '3,7'
      }

      FIND_SHOP_ORDER_PAGE(params, 1, 1)
        .then(r => {
          if (r.data.code === '0') {
            vm.countForm.orderTotal = r.data.data.total
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 订单数
    initRequest () {
      const vm = this
      vm.shopSalesCountDay1() // 今天订单统计
      vm.rebateASalesCountDay1() // 今天返佣金额
      vm._getVIPNumPeople() // 会员数
      vm.shopEvaluationCount() // 评分率
      vm.shopCollectionCount() // 收藏数
      vm.shopOrderCount() // 订单数
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';
.bannerTop {
  position: relative;
  width: 100%;
  height: 100px;
  img {
    width: 100%;
    height: 100px;
    position: absolute;
    z-index: -1;
    top: 0;
  }
  .contDiv {
    width: 100%;
    height: 100px;
    display: flex;
    div {
      width: 33.33%;
      height: 100px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-end;
      color: #fff;
      font-size: 14px;
      span {
        font-size: 14px;
        margin: 8px 0;
      }
    }
  }
}
.infoShow {
  margin: 10px 0;
  width: 100%;
  display: flex;
  border-bottom: 6px solid #efefef;

  div {
    width: 25%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    p {
      color: #000;
      margin-bottom: 5px;
    }
    span {
      color: #9a9a9a;
    }
  }
}
.showDataType {
  width: 100%;
  display: flex;
  > div {
    width: 33.33%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-bottom: 3px solid #fff;
    > .top {
      width: 100%;
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      color: #a1a1a1;
      img {
        width: 15px;
        height: 15px;
        margin-right: 5px;
      }
    }
    p {
      margin-bottom: 10px;
    }
  }
  > .isClick {
    border-bottom: 3px solid #6371fd;
  }
}

.chart-wrap {
  padding: 0 15px;
  width: 100%;
  height: 300px;
}

.showDataDate {
  width: 100%;
  display: flex;
  border-top: 1px solid #e6e6e6;
  border-bottom: 6px solid #efefef;
  > div {
    width: 25%;
    line-height: 30px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #9c9c9c;
    font-size: 13px;
  }
  > div:nth-child(2) {
    border-left: 1px solid #e6e6e6;
  }
  > div:nth-child(3) {
    border-left: 1px solid #e6e6e6;
    border-right: 1px solid #e6e6e6;
  }
  > .isClick {
    color: $blue;
  }
}
</style>
